package com.powernode.map.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.powernode.common.execption.PowerException;
import com.powernode.common.result.ResultCodeEnum;
import com.powernode.map.service.MapService;
import com.powernode.model.form.map.CalculateDrivingLineForm;
import com.powernode.model.vo.map.DrivingLineVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    @Resource
    private RestTemplate restTemplate;

    @Value("${tencent.map.key}")
    private String key;

    /**
     * 估算配送路线
     */
    @Override
    public DrivingLineVo calculateLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        //向腾讯地图发送请求 获取结果
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";

        //处理参数
        HashMap<String, String> map = new HashMap<>();
        map.put("from", calculateDrivingLineForm.getStartPointLatitude() + "," + calculateDrivingLineForm.getStartPointLongitude());
        map.put("to", calculateDrivingLineForm.getEndPointLatitude() + "," + calculateDrivingLineForm.getEndPointLongitude());
        map.put("key", key);

        //发送请求
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);

        //判断腾讯地图返回的结果
        if (result.getIntValue("status") != 0) {
            throw new PowerException(ResultCodeEnum.MAP_FAIL);
        }

        //获取第一条最佳方案
        JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);

        //将路径信息封装成DrivingLineVo对象
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        
        //路径总距离 米
        BigDecimal meter = route.getBigDecimal("distance");
        //转成千米
        BigDecimal kilometer = meter.divide(BigDecimal.valueOf(1000)).setScale(2, RoundingMode.HALF_UP);
        drivingLineVo.setDistance(kilometer);

        //配送时间
        drivingLineVo.setDuration(route.getBigDecimal("duration"));

        //标点串
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));

        return drivingLineVo;

    }
}
